package com.wstuo.common.sla.dao;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.util.StringUtils;

import com.wstuo.common.sla.dto.SLAContractQueryDTO;
import com.wstuo.common.sla.entity.SLAContract;
import com.wstuo.common.dao.BaseDAOImplHibernate;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.util.DaoUtils;

/**
 * SLA服务协议DAO类.
 * @author QXY
 *
 */
public class SLAContractDAO extends BaseDAOImplHibernate<SLAContract>
    implements ISLAContractDAO {
	private static final Logger LOGGER = Logger.getLogger(SLAContractDAO.class);
	/**
	 * 获取SLA编号
	 */
    public static Long latesSLANo=0L;

	/**
	 * 分页查找数据.
	 * @param queryDTO 查询DTO
	 * @param start 开始数据行
	 * @param limit 每页数据条数
	 * @return PageDTO 分页数据
	 */
    public PageDTO findPager(SLAContractQueryDTO queryDTO, int start,
        int limit,String sidx,String sord) {

        DetachedCriteria dc = DetachedCriteria.forClass(SLAContract.class);

        if (queryDTO != null) {

            if (queryDTO.getOrgNo() != null && StringUtils.hasText(queryDTO.getOrgNo().toString())) {
            	dc.createAlias("byServiceOrg", "org")
                .add(Restrictions.eq("org.orgNo", queryDTO.getOrgNo()));
            }
            if (queryDTO.getOrgNos() != null && queryDTO.getOrgNos().length>0) {
            	dc.createAlias("byServiceOrg", "org");
            	dc.setFetchMode( "byServiceOrg", FetchMode.SELECT);
                dc.add(Restrictions.in("org.orgNo", queryDTO.getOrgNos()));
            }
            if (queryDTO.getDirNos() != null && queryDTO.getDirNos().length>0) {
            	dc.createAlias("serviceDirs", "dir");
            	dc.setFetchMode( "serviceDirs", FetchMode.SELECT);
                dc.add(Restrictions.in("dir.eventId", queryDTO.getDirNos()));
            }
            if (queryDTO.getDcode() != null && StringUtils.hasText(queryDTO.getDcode().toString())) {

            	dc.createAlias("slaSort", "slaSort")
                .add(Restrictions.eq("slaSort.dcode",
                      queryDTO.getDcode()));
            }
            if (queryDTO.getContractNo() != null && queryDTO.getContractNo()!=0) {
            	dc.add(Restrictions.eq("contractNo", queryDTO.getContractNo()));
            }
            if (StringUtils.hasText(queryDTO.getContractName())) {
                dc.add(Restrictions.like("contractName",
                        queryDTO.getContractName(), MatchMode.ANYWHERE));
            }
        }
        //排序
        dc = DaoUtils.orderBy(sidx, sord, dc);
        PageDTO p = new PageDTO();
        if(queryDTO!=null && queryDTO.getOrgNos()!=null && queryDTO.getOrgNos().length>0){
        	p=super.findPageByCriteria( dc,start,limit,"contractName");
        }else{
        	p=super.findPageByCriteria( dc, start, limit);
        }
        return p;
    }

    /**
     * 根据规则包名查找SLA信息.
     * @param rulePackageNo 规则包No
     * @return SLAContract
     */
	@SuppressWarnings("unchecked")
	public SLAContract findByRulePackageNo(Long rulePackageNo) {

			
		  List<SLAContract> slaContract = super.getHibernateTemplate().find(" from SLAContract sl where sl.rulePackage.rulePackageNo="+rulePackageNo);
		  
		
		  if(slaContract.size()>0){
			  
			  return slaContract.get(0);
			  
		  }else{
			  LOGGER.error("根据规则包名查找SLA信息取值为空！");
			  return null;
		  }
		  
	}
	
	
	/**
	 * 根据服务机构查找SLA.
	 * @param serviceOrgName
	 * @return  SLAContract
	 */
	public SLAContract findByServiceOrgName(String serviceOrgName){
		
		final DetachedCriteria dc = DetachedCriteria.forClass(SLAContract.class);
		dc.createAlias("serviceOrg",  "serOrg").add(Restrictions.eq( "serOrg.orgName",serviceOrgName));
		
		List<SLAContract> slaList=getHibernateTemplate().findByCriteria(dc);
		

		if(slaList!=null && slaList.size()>0){
			
			return slaList.get(0);
		}
		
		return null;
	}
	
	
	
    /**
     * 根据服务机构和被服务机构查找SLA
     * @param servicesNo
     * @param byServicesNo
     * @return SLAContract
     */
	@SuppressWarnings("unchecked")
	public SLAContract findByServicesNo(Long servicesNo,Long byServicesNo) {

		final DetachedCriteria dc = DetachedCriteria.forClass(SLAContract.class);
		dc.createAlias("serviceOrg",  "serOrg").add(Restrictions.eq( "serOrg.orgNo",servicesNo));
		dc.createAlias("byServiceOrg",  "bySerOrg").add(Restrictions.eq( "bySerOrg.orgNo",byServicesNo));
		
		dc.add(Restrictions.le("dataFlag",Byte.parseByte("98")));
		
		List<SLAContract> slaList=getHibernateTemplate().findByCriteria(dc);
		

		if(slaList!=null && slaList.size()>0){
			
			return slaList.get(0);
			
			
		}
		return null;
			

	}
    /**
     * 设置值.
     * @param latesSLANo
     */
    public void setLatesSLANo(Long latesSLANo) {
    	
    	synchronized(this){
    		SLAContractDAO.latesSLANo = latesSLANo;
    	}
	}

	/**
     * 累加SLA编号.
     */
    public void increment(){
    	synchronized(this){
    		latesSLANo+=1;
    	}
    }
    
    /**
     * 取得最新No.
     * @return Long
     */
    public Long getLatesSLANo() {
		
    	synchronized(this){
    		return latesSLANo;
    	}
    	
    	
	}

    
    /**
     * 取得下一个编号.
     * @return Long
     */
    public Long getNextResNo(){
    	Long v = 1L;
    	final String hql = "select max(slac.contractNo) from SLAContract slac";
    	List list=getHibernateTemplate().find(hql);
    	
    	if(list!=null && list.size()>0){
    		Number n = (Number)list.get(0);
    		if (n!=null) {
    			v = n.longValue()+1;
    		}
    	}
    	return v;
    }
    

    
    /**
     * 重写SAVE方法.
     */
     @Override
     public void save(SLAContract entity){
     	
     	if(entity.getContractNo()==null || entity.getContractNo()==0){
     		entity.setContractNo(getLatesSLANo());
     	}else{
     		
     		if(entity.getContractNo()>getLatesSLANo()){
     			
     			setLatesSLANo(entity.getContractNo());
     		}
     		
     	}
     	
     	super.save(entity);
     	increment();//自增1.
     	
     }
     
     /**
      * 重写MERGE方法.
      */
     @Override
     public SLAContract merge(SLAContract entity){
    	 
    	 
    	if(entity.getContractNo()!=null){
      		if(entity.getContractNo()>=getLatesSLANo()){
      			setLatesSLANo(entity.getContractNo()+1);
      		}
      	}else{
      		increment();//自增1.
    	}
    	 
    	 return super.merge(entity);
     }
	
     
     
     /**
      * 查询服务机构是否存在SLA。
      * @param orgNo
      * @return Boolean
      */
     public Boolean isHasSmaeServiceOrg(Long orgNo,Long slaNo){
     	
     	final DetachedCriteria dc = DetachedCriteria.forClass( SLAContract.class );
     	dc.createAlias("serviceOrg", "so");
     	dc.add(Restrictions.eq("so.orgNo", orgNo));
     	
     	if(slaNo!=null){
     		dc.add(Restrictions.not(Restrictions.eq("contractNo", slaNo)));
     	}
     	
     	Criteria criteria=dc.getExecutableCriteria(getSession());
     	int rowCount=((Number)criteria.setProjection(Projections.rowCount()).uniqueResult()).intValue();
     	
     	if(rowCount>0){
     		return true;
     	}else{
     		return false;
     	}
     }
     
     
     
     
     
     
}